package bg.ittalents.homework.airport;

public class Runway {

	private boolean isOpen;
	private boolean isTaken;
	private long closedUntil;
	private long takenUntil;
	private int id;

	public Runway(int id) {
		this.id = id;
		isOpen = true;
		isTaken = false;
	}

	public int getId() {
		return id;
	}

	public boolean isOpen() {
		return isOpen;
	}

	public boolean isTaken() {
		return isTaken;
	}

	public boolean isAvailable() {
		return isOpen && !isTaken;
	}

	public void open() {
		closedUntil = 0;
		this.isOpen = true;
	}

	public void close(long period) {
		if (period > 0) {
			isOpen = false;
			closedUntil = period;
		}
	}

	public void reserve(long period) {
		if (isOpen && !isTaken && period > 0) {
			isTaken = true;
			takenUntil = period;
		}
	}

	void decrementTimers() {
		if (closedUntil > 0) {
			closedUntil--;
		}

		if (takenUntil > 0) {
			takenUntil--;
		}

		if (closedUntil == 0) {
			open();
		}

		if (takenUntil == 0) {
			isTaken = false;
		}
	}

	public long notAvailableUntil() {

		if (isOpen && !isTaken) {
			return 0;
		}

		if (closedUntil > takenUntil) {
			return closedUntil;
		}
		return takenUntil;
	}

}
